import pyaudio
import wave
import os
from PyCmpltrtok.common import rand_name_on_now, get_dir_name_ext

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = 4
XDIR, XNAME, XEXT = get_dir_name_ext(os.path.abspath(__file__))
SAVE_DIR = os.path.join(XDIR, '_save', XNAME)
os.makedirs(SAVE_DIR, exist_ok=True)
WAVE_OUTPUT_FILENAME = os.path.join(SAVE_DIR, 'pyp_stop_' + rand_name_on_now() + ".wav")

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print(f"start recording {WAVE_OUTPUT_FILENAME}......")

frames = []

N_ITER = int(RATE / CHUNK * RECORD_SECONDS)
HALF = N_ITER // 2
QUATER = N_ITER // 4
HALF_AND_QUATER = HALF + QUATER
for i in range(0, N_ITER):
    data = stream.read(CHUNK)
    # print('len', len(data))  # 2048
    # print('type(data)', type(data))  # bytes
    frames.append(data)
    print('.', end='', flush=True)
    if i == QUATER - 1:
        print('25%', end='', flush=True)
    elif i == HALF - 1:
        print('50%', end='', flush=True)
    elif i == HALF_AND_QUATER - 1:
        print('75%', end='', flush=True)
print('100%')

print("Sampling over!")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

print('Over')
